const Order = require('../database/orderDao');
const Room = require('../database/roomDao');
const expree = require('express')
const router = expree.Router()
const authMiddleware = require('../middleware/auth')
// 创建订单
router.post('/create', authMiddleware(['customer']), async (req,res) => {
  try {
      const { room_id, start_time, end_time, total_price,userId } = req.body;
      const customer_id = userId;
      // 检查会议室是否可用
      const isAvailable = await Order.checkRoomAvailability(room_id, start_time, end_time);
      if (!isAvailable) {
        return res.status(400).json({ error: '会议室在该时间段不可用' });
      }
      
      // 检查会议室状态
      const room = await Room.findById(room_id);
      if (room.status !== 'idle') {
        return res.status(400).json({ error: '会议室当前不可预订' });
      }
      
      // 创建订单
      const orderId = await Order.create({
        room_id,
        customer_id,
        start_time,
        end_time,
        total_price
      });
      
      // 更新会议室状态为锁定
      await Room.updateStatus(room_id, 'locked');
      
      res.json({ order_id: orderId, message: '订单创建成功，请在30分钟内完成支付' });
    } catch (error) {
      console.log(error)
      res.status(500).json({ error: '服务器错误' });
    }
})
// 查询订单（根据
router.get('/getorder', authMiddleware(['customer']), async (req,res) => {
    try {
      const { status } = req.query;
      const customer_id = req.query.userId;
      
      const orders = await Order.findByCustomer(customer_id, status);
      res.json(orders);
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 获取全部订单
router.get('/getOrderByRoomId',authMiddleware(['employee']),async (req,res) => {
  try {
    const room_id = req.query.room_id;
    const result = await Order.findByRoomId(room_id)
    res.json(result)
  }catch(error) {
    res.status(500).json({ error: '服务器错误' });
  }
})
// 取消订单
router.put('/:order_id/cancel', authMiddleware(['customer']), async (req,res) => {
    try {
      const orderId = req.params.order_id;
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({ error: '订单不存在' });
      }
      
      // 检查订单状态
      if (order.order_status !== 'unpaid' && order.order_status !== 'paid') {
        return res.status(400).json({ error: '订单无法取消' });
      }
      
      // 取消订单
      await Order.cancel(orderId);
      
      // 如果会议室状态是locked或booked，恢复为idle
      if (order.order_status === 'unpaid') {
        await Room.updateStatus(order.room_id, 'idle');
      }
      
      res.json({ message: '取消申请已提交，等待审核' });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 支付
router.put('/:order_id/pay', authMiddleware(['customer']), async (req,res) => {
    try {
      const orderId = req.params.order_id;
      
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({ error: '订单不存在' });
      }
      
      if (order.order_status !== 'unpaid') {
        return res.status(400).json({ error: '订单状态不允许支付' });
      }
      
      // 支付订单
      await Order.pay(orderId);
      
      // 更新会议室状态为booked
      await Room.updateStatus(order.room_id, 'booked');
      
      res.json({ message: '支付成功' });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
router.put('/:order_id/refund',authMiddleware(['employee', 'admin']), async (req,res) => {
    try {
      const orderId = req.params.order_id;
      const { status } = req.body;
      
      const order = await Order.findById(orderId);
      if (!order) {
        return res.status(404).json({ error: '订单不存在' });
      }
      
      if (order.order_status !== 'canceled' || order.refund_status !== 'pending') {
        return res.status(400).json({ error: '退款申请无法处理' });
      }
      
      // 处理退款
      await Order.updateRefundStatus(orderId, status);
      
      if (status === 'approved') {
        // 退款成功，更新会议室状态
        await Room.updateStatus(order.room_id, 'idle');
        res.json({ message: '退款已批准', refund_amount: order.total_price });
      } else {
        res.json({ message: '退款已拒绝' });
      }
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})
// 定时任务
router.post('/auto-release',async (req,res) => {
    try {
      const count = await Order.autoReleaseLockedRooms();
      res.json({ message: `已自动释放${count}个锁定会议室` });
    } catch (error) {
      res.status(500).json({ error: '服务器错误' });
    }
})

module.exports = router;